<?php
session_start();

require_once("connexion.php");

if (isset($_POST['function']) && $_POST['function'] != '') {
    switch ($_POST['function']) {
        case "loadNbEpisode": echo db_getNbEpisode($_POST['saison'],$_POST['episode']);
            break;
        case "saveTimeline":  saveTimeline($_POST['saison'], $_POST['episode']);
            break;
        case "changeEpisode":  changeEpisode($_POST['episode']);
            break;
        case "getNbEpisode": echo getNbEpisode($_POST['saison']);
            break;
    }
}

function db_getNbEpisode($saison, $episode) {
    global $db;
    $_SESSION["saison"]=$saison;
    if($episode!=null){$_SESSION["episode"]=$episode;}
    else{$_SESSION["episode"]="1";}
    
    $request = "select max(numeroEpisode) as nbEpisode from episode where idSaison = $saison";
    $query = $db->query($request);
    $data = $query->fetch();
    $nbEpisode = $data["nbEpisode"];
    
    return $nbEpisode;
}

function db_getNbSaison() {
    global $db;

    $request = "select max(idSaison) as nbSaison from episode";
    $query = $db->query($request);
    $data = $query->fetch();
    $nbSaison = $data["nbSaison"];
    
    return $nbSaison;
}

function saveTimeline($saison, $episode) {
    global $db;
    $_SESSION["saison"]=$saison;
    $_SESSION["episode"]=$episode;
    
        $idUser = $_SESSION['idUser'];
        $idEpisode = "SELECT idEpisode as timeline from episode where idSaison = $saison and numeroEpisode = $episode";
        $request = "UPDATE user SET timeline=($idEpisode) WHERE idUser = $idUser";
        
        $query = $db->query($request);
}

function changeEpisode($episode){
    $_SESSION["episode"]=$episode;
}

function getNbEpisode($saison) {
    global $db;
    $request = "select max(numeroEpisode) as nbEpisode from episode where idSaison = $saison";
    $query = $db->query($request);
    $data = $query->fetch();
    $nbEpisode = $data["nbEpisode"];
//    var_dump($nbEpisode);
    return $nbEpisode;
}

?>